package com.example.bbs.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.UUID;


/**
 * 邮件发送工具类
 * 
 * @author VC
 *
 */
public class MailUtil {
	// SMTP服务器地址
	private static final String SMTP_HOST = "smtp.qq.com";
	// 发件人邮箱
	private static final String FROM = "2122877473@qq.com";
	// 邮箱密码
	protected static final String PWD = "xyreknbsmuaabghd";

	/**
	 * 使用SMTP协议发送邮件
	 * 
	 * @param to
	 *            收件人邮箱地址
	 * @param title
	 *            邮件标题
	 * @param content
	 *            邮件内容
	 * @throws Exception
	 */
	public static void sendMail(String to, String title, String content) throws Exception {
		// 创建配置文件对象
		Properties prop = new Properties();
		// SMTP服务器地址
		prop.put("mail.smtp.host", SMTP_HOST);
		// 打开认证
		prop.put("mail.smtp.auth", "true");
		// 创建SSL认证
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		prop.put("mail.smtp.ssl.enable", "true");
		prop.put("mail.smtp.ssl.socketFactory", sf);
		// 创建会话
		Session session = Session.getDefaultInstance(prop, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名密码配置
				return new PasswordAuthentication(FROM, PWD);
			}
		});
		// 创建邮件对象
		Message message = new MimeMessage(session);
		// 设置发件人
		message.setFrom(new InternetAddress(FROM));
		// 设置接收人
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		// 设置邮件主题
		message.setSubject(title);
		// 设置邮件内容
		message.setContent(content, "text/html;charset=UTF-8");
		// 发送邮件
		Transport.send(message);

	}

	public static void main(String[] args) {
		//生成一个激活码
		String code = UUID.randomUUID().toString();

		String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost:8080/Mail/ActiveServlet?code="
				+ code + "'>http://localhost:8080/Mail/mail/active.action?code=" + code + "</href></h3></body></html>";
		try {
			sendMail("2122877473@qq.com", "账号激活", content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
